package com.design.android.personnel.ui.edit;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.Navigation;
import com.design.android.personnel.AppContext;
import com.design.android.personnel.R;
import com.design.android.personnel.bean.PersonnelInfo;
import com.design.android.personnel.database.PersonnelInfoOperate;

import java.util.Date;

import static android.app.Activity.RESULT_OK;

public class EditFragment extends Fragment {
    private static final int RESULT_LOAD_IMAGE = 10101;

    private EditViewModel editViewModel;

    private EditText nameEditText;
    private EditText phoneEditText;
    private Spinner sexSpinner;
    private EditText addrEditText;
    private ImageView avatarImageView;
    private Button updateButton;

    private PersonnelInfoOperate personnelInfoOperate;

    // 头像
    private Bitmap avatarBitmap;

    // 修改的人员信息
    private PersonnelInfo personnelInfo;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
            ViewGroup container, Bundle savedInstanceState) {
        editViewModel = ViewModelProviders.of(this).get(EditViewModel.class);
        View root = inflater.inflate(R.layout.fragment_edit, container, false);

        // 在fragment中的 actionbar 点击返回箭头事件处理
        setHasOptionsMenu(true);

        personnelInfoOperate = new PersonnelInfoOperate(getContext());

        nameEditText = root.findViewById(R.id.username);
        phoneEditText = root.findViewById(R.id.phone);
        sexSpinner = root.findViewById(R.id.register_spinner);
        addrEditText = root.findViewById(R.id.addr);
        avatarImageView = root.findViewById(R.id.avatar);
        updateButton = root.findViewById(R.id.update);

        updateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updatePersonnelInfo();
            }
        });

        // 点击选择图片
        avatarImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //一个重定向打开系统图库
                Intent i = new Intent(Intent.ACTION_PICK,
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
        // 长按清除图片
        avatarImageView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                avatarImageView.setImageDrawable(getContext().getDrawable(R.mipmap.ic_image));
                avatarBitmap = null;
                return true;
            }
        });

        sexSpinner.setAdapter(new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1,
                new String[]{"男", "女"}));

        Bundle bundle = getArguments();

        // 接收参数
        if (bundle != null) {
            personnelInfo = (PersonnelInfo) bundle.getSerializable("personnelInfo");
            Integer id = personnelInfo.getId();
            System.out.println("getSerializable id = " + id);
            initViewText(personnelInfo);
        } else {
            back();
        }
        return root;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            try {
                Cursor cursor = getContext().getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String loadImagePath = cursor.getString(columnIndex);
                cursor.close();

                // 从手机选择图片显示到 avatarImageView
                // System.out.println("加载图片路径:"+picturePath);
                avatarBitmap = BitmapFactory.decodeFile(loadImagePath);
                avatarImageView.setImageBitmap(avatarBitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void updatePersonnelInfo() {
        String phone = phoneEditText.getText().toString();
        String name = nameEditText.getText().toString();
        String sex = sexSpinner.getSelectedItem().toString();
        String addr = addrEditText.getText().toString();

        if (name.isEmpty()) {
            nameEditText.requestFocus();
            nameEditText.setError("姓名不能为空！");
            return;
        }
        if (phone.isEmpty()) {
            phoneEditText.requestFocus();
            phoneEditText.setError("手机号不能为空！");
            return;
        }
        if (addr.isEmpty()) {
            addrEditText.requestFocus();
            addrEditText.setError("地址不能为空！");
            return;
        }

        if (avatarBitmap == null) {
            Toast.makeText(getContext(), "请选择图片", Toast.LENGTH_SHORT).show();
            return;
        }

        personnelInfo.setUserId(AppContext.getLoggedInUserId());
        personnelInfo.setAvatar(avatarBitmap);
        personnelInfo.setPhone(phone);
        personnelInfo.setName(name);
        personnelInfo.setSex(sex);
        personnelInfo.setAddr(addr);
        personnelInfo.setUpdateTime(new Date());

        personnelInfoOperate.update(personnelInfo);

        Toast.makeText(getContext(), "更新成功", Toast.LENGTH_SHORT).show();

        // 短暂延时后返回上个页面
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                back();
            }
        }, 2000);
    }

    public void initViewText(PersonnelInfo personnelInfo) {
        nameEditText.setText(personnelInfo.getName());
        phoneEditText.setText(personnelInfo.getPhone());
        addrEditText.setText(personnelInfo.getAddr());

        Bitmap avatar = personnelInfo.getAvatar();
        avatarImageView.setImageBitmap(avatar);
        avatarBitmap = avatar;

        String sex = personnelInfo.getSex();
        if (sex.equals("男")) {
            sexSpinner.setSelection(0);
        } else if (sex.equals("女")) {
            sexSpinner.setSelection(1);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                back();
                return true;
            default:
        }
        return super.onOptionsItemSelected(item);
    }

    private void back() {
        Navigation.findNavController(getView()).navigateUp();
    }
}
